package com.hx.interview;

import java.io.*;
import java.util.Stack;

/**
 * @author MinghuaChen
 * @date 2022-02-28 21:35
 * @description 将一个20MB的文本文件倒序写入另一个文件，比如“abcde”写成“edcba”
 * 注意代码质量，节省内存；10分
 */
public class ReverseText {
    public static void main(String[] args) {
        File file = new File("D://a.txt");
        FileReader reader = null;

        try {
            reader = new FileReader(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("打开文件异常", e);
        }

        BufferedReader bufferedReader = new BufferedReader(reader);
        String readString = null;
        Stack<String> stack = new Stack<>();

        try {
            while ((readString = bufferedReader.readLine()) != null) {
                String reverse = new StringBuffer(readString).reverse().toString();
                stack.add(reverse);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取文件出现异常", e);
        }

        try {
            bufferedReader.close();
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException("关闭读取文件流出现异常", e);
        }

        File targetFile = new File("D://b.txt");
        FileWriter fileWriter = null;

        try {
            fileWriter = new FileWriter(targetFile);
        } catch (IOException e) {
            throw new RuntimeException("创建输出文件出现异常", e);
        }

        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        while (!stack.empty()) {
            String popString = stack.pop();
            try {
                bufferedWriter.write(popString);
                bufferedWriter.write("\r\n");
            } catch (IOException e) {
                throw new RuntimeException("写入文件时出现异常", e);
            }
        }

        try {
            // 刷盘
            bufferedWriter.flush();
            // 关闭流
            bufferedWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException("关闭输出文件流出现异常", e);
        }
    }
}
